<template>
    <div>
        <input type="text" v-model="message">
        <!-- <input type="text" v-model="user"> -->

        <p><input type="button" @click="send" value="发送"></p>
        <p><input type="button" @click="close_socket" value="关闭"></p>
    </div>
</template>


<script>
export default {
    name:'tongxun',
    data() {
        return {
            message:'',
            testsocket:'',
            // user:''
        }
    },
    methods:{
        send(){
           
        //    send  发送信息
        //    close 关闭连接
            // var data1 = {"message":this.message,"to_user":this.user}
           
            // this.testsocket.send(JSON.stringify(data1))
            this.testsocket.send(this.message)
            this.testsocket.onmessage = (res) => {
                console.log("WS的返回结果",res.data);         
            }

        },
        close_socket(){
            this.testsocket.close()
        },
        generate_uuid: function() {
            var d = new Date().getTime();
            if (window.performance && typeof window.performance.now === "function") {
                d += performance.now(); //use high-precision timer if available
            }
            var uuid = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(
                /[xy]/g,
                function(c) {
                var r = (d + Math.random() * 16) % 16 | 0;
                d = Math.floor(d / 16);
                return (c == "x" ? r : (r & 0x3) | 0x8).toString(16);
                }
            );
            return uuid;
        },

    },
    mounted(){
        this.testsocket = new WebSocket("ws://127.0.0.1:8000/ws/") 
        // var username = this.generate_uuid();
        // console.log(username)
        // this.testsocket = new WebSocket("ws://127.0.0.1:8000/ws/"+ username +"/") 
        // console.log(this.testsocket)

      	// this.testsocket.onmessage = (res) => {
        //         console.log("WS的返回结果",res.data);         
        //     }
      	
        // onopen     定义打开时的函数
        // onclose    定义关闭时的函数
        // onmessage  定义接收数据时候的函数
        this.testsocket.onopen = function(){
            console.log("开始连接socket")
        },
        this.testsocket.onclose = function(){
            console.log("socket连接已经关闭")
        }
        this.testsocket.onmessage = (res) => {
            console.log('ws返回结果为',res.data)
        }
    }
}
</script>